from flask import Blueprint, make_response, json, request, session, g, jsonify
from utils.ResponseResult import success_json_result, fail_json_result
from models.BookSystemModels import UserModel
from decorators.decorators import login_required

# 创建权限蓝图
bp = Blueprint("auth_views_bp", __name__, url_prefix="/auth")


@bp.route("/login", methods=["POST"])
def login():
    user = getattr(g, "user")
    if user:
        return fail_json_result(msg="用户已登录,不能重复登录")
    data = request.get_json()
    username = data.get("userName")
    password = data.get("password")
    # 登录方式：0:工号密码 1:邮箱 2:短信
    login_mode = data.get("loginMode")
    if not username or not password:
        return fail_json_result(msg="用户名或密码不能为空")
    if login_mode not in ["0", "1", "2"]:
        login_mode = "0"
    if login_mode == "0":
        return user_password_login(username, password)
    if login_mode == "1":
        user_email_login(username)
    if login_mode == "2":
        user_sms_login(username)


def user_password_login(username, password):
    user = UserModel.query.filter_by(user_no=username).first()
    if not user:
        return fail_json_result(msg="无效用户名,户名不存在")
    if user.password != password:
        return fail_json_result(msg="密码错误")
    session["user_id"] = user.id
    return success_json_result(data=user.id, msg="登录成功")


def user_email_login(email):
    # todo: 验证email是否存在
    return success_json_result(data="login success！！！", msg="登录成功")


def user_sms_login(phone):
    # todo:验证phone是否存在
    return success_json_result(data="login success！！！", msg="登录成功")


@bp.route("/test")
@login_required
def test():
    user = g.user
    user1 = {
        "id": user.id,
        "name": user.name,
        "password": user.password,
        "age": user.age,
        "createTime": user.create_time.strftime("%Y-%m-%d %H:%M:%S")
    }
    return success_json_result(data=user1)


@bp.route("/setSession")
def setSession():
    session["user_id"] = 1
    return success_json_result(data='set session success')


@bp.route("/test1")
def test1():
    user_id = session.get("user_id")
    return success_json_result(data=user_id)


@bp.route("/test2")
def test2():
    return jsonify("这个是测试汉语的请求")


@bp.route("/logout")
def logout():
    session.clear()
    return success_json_result(msg="退出登录成功")


@bp.route('/api/json')
def jsonTest():
    data = {
        "code": 200,
        "message": "你好, 世界",
        "success": True
    }
    response = make_response(json.dumps(data, ensure_ascii=False))
    response.mimetype = "application/json"
    response.charset = "utf-8"
    return response
